package com.medicine.service.impl;

import com.medicine.constant.MessageConstant;
import com.medicine.constant.StatusConstant;
import com.medicine.dto.MedicineDTO;
import com.medicine.entity.Medicine;
import com.medicine.exception.DeletionNotAllowedException;
import com.medicine.mapper.MedicineMapper;
import com.medicine.service.MedicineService;
import com.medicine.vo.MedicineVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MedicineServiceImpl implements MedicineService {

    @Autowired
    private MedicineMapper medicineMapper;

    /**
     * 新增药品
     *
     * @param medicineDTO
     */
    @Transactional
    public void save(MedicineDTO medicineDTO) {

        Medicine medicine = new Medicine();

        BeanUtils.copyProperties(medicineDTO, medicine);

        //向药品表插入1条数据
        medicineMapper.insert(medicine);
    }


    /**
     * 药品批量删除
     *
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前药品是否能够删除---是否存在起售中的药品？？
        for (Long id : ids) {
            Medicine medicine = medicineMapper.getById(id);
            if (medicine.getStatus() == StatusConstant.ENABLE) {
                //当前药品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.MEDICINE_ON_SALE);
            }
        }

        //删除药品表中的药品数据
        for (Long id : ids) {
            medicineMapper.deleteById(id);
        }
    }

    /**
     * 根据id修改药品基本信息
     *
     * @param medicineDTO
     */
    public void update(MedicineDTO medicineDTO) {
        Medicine medicine = new Medicine();
        BeanUtils.copyProperties(medicineDTO, medicine);

        //修改药品表基本信息
        medicineMapper.update(medicine);
    }

    /**
     * 药品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Medicine medicine = Medicine.builder()
                .id(id)
                .status(status)
                .build();
        medicineMapper.update(medicine);
    }

    /**
     * 条件查询药品
     * @param medicine
     * @return
     */
    public List<MedicineVO> listWithFlavor(Medicine medicine) {
        List<Medicine> medicineList = medicineMapper.list(medicine);

        List<MedicineVO> medicineVOList = new ArrayList<>();

        for (Medicine d : medicineList) {
            MedicineVO medicineVO = new MedicineVO();
            BeanUtils.copyProperties(d, medicineVO);
            medicineVOList.add(medicineVO);
        }

        return medicineVOList;
    }
}